﻿using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using Kiiro.Common.Entities;
using Kiiro.Common.Utility;
using Kiiro.Model;
using Kiiro.SiteDefinition.ControlTemplates;
using Kiiro.SiteDefinition.Core;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

namespace Kiiro.SiteDefinition.ProjectPages
{
    public partial class EditProjectSettings : BasePage
    {
        #region Properties
        public Project Project
        {
            get;
            set;
        }

        public CustomFieldCollection CustomFields
        {
            get { return ( CustomFieldCollection ) v2CustomFieldCollection; }
        }

        public AttachmentControl Attachments
        {
            get { return ( AttachmentControl ) attachments; }
        }

        public NavigationSub NavigationSub
        {
            get { return KiiroMaster.NavigationSub; }
        }

        public FormButtons Buttons
        {
            get { return ( FormButtons ) v2FormButtons; }
        }
        #endregion

        #region Page Events
        protected override void OnInit ( EventArgs e )
        {
            base.OnInit ( e );
            CustomFields.ControlMode = SPControlMode.Edit;
            NavigationSub.DeleteButton.ControlMode = SPControlMode.Edit;
            Buttons.SaveButton.ControlMode = SPControlMode.Edit;
            Buttons.CancelButton.ControlMode = SPControlMode.Edit;
        }

        protected void Page_Load ( object sender, EventArgs e )
        {
            Attachments.MaxLength = 1;
            Attachments.FileFormat = "mpp";

            CustomFields.EntityType = typeof ( Project );
            CustomFields.Title = "Additional Information";

            SPContext context = CustomModel.GetCustomFieldsContext ( typeof ( Project ), ItemId, Context, SiteCollectionId, ServerRelativeUrl );
            context.FormContext.FormMode = SPControlMode.Edit;

            Buttons.SaveButton.ItemId = ItemId;
            Buttons.SaveButton.ItemContext = context;
            Buttons.SaveButton.RenderContext = context;

            Buttons.CancelButton.ItemContext = context;
            Buttons.CancelButton.RenderContext = context;
            Buttons.CancelButton.RedirectUrl = Cancel ( );

            NavigationSub.DeleteButton.ItemContext = context;
            NavigationSub.DeleteButton.RenderContext = context;

            if ( PermissionBitsProjects [ 2 ] )
            {
                Project = ProjectsModel.GetByServerRelativeWebUrl ( SiteCollectionId, ServerRelativeUrl );
                AddCommandButtons ( );

                if ( !Page.IsPostBack )
                {
                    PopulateForm ( );
                }
            }
            else
            {
                Response.Redirect ( ServerRelativeUrl );
            }

            litTitle.Text = "Project Settings";
            if ( KiiroMaster.V2Header.Project != null && !string.IsNullOrEmpty ( KiiroMaster.V2Header.Project.Title ) )
            {
                litTitle.Text = KiiroMaster.V2Header.Project.Title + " - Project Settings";
            }
        }

        protected override void OnPreRender ( EventArgs e )
        {
            base.OnPreRender ( e );

            // if Project is Closed disable all fields except the Project Status 
            if (KiiroMaster != null
                && KiiroMaster.V2Header != null
                && KiiroMaster.V2Header.Project != null
                && Project.ProjectStatus == ProjectStatus.Closed ||
                LicenseKeyBits.Contains(true))
            {
                txtProjectTitle.Enabled = false;
                txtStartDate.Enabled = false;
                txtEndDate.Enabled = false;
                rblTimeMetric.Enabled = false;
                txtProjectDescription.Enabled = false;
                txtProjectSummary.Enabled = false;

                txtStartDate.CssClass = txtStartDate.CssClass.Replace("datepicker", "");
                txtEndDate.CssClass = txtEndDate.CssClass.Replace("datepicker", "");

                pnlAttachments.Visible = !string.IsNullOrEmpty ( Project.ProjectPlanFileUrl );
                Attachments.ControlMode = PageMode.Display;
                Attachments.Disabled = true;

                ckbWPSandboxEnabled.Enabled = false;
                txtWPSandboxNavText.Enabled = false;
            }
            else
            {
                txtProjectTitle.Enabled = true;
                txtStartDate.Enabled = true;
                txtEndDate.Enabled = true;
                rblTimeMetric.Enabled = true;
                txtProjectDescription.Enabled = true;
                txtProjectSummary.Enabled = true;

                pnlAttachments.Visible = true;
                Attachments.ControlMode = PageMode.Edit;
                Attachments.Disabled = false;

                ckbWPSandboxEnabled.Enabled = true;
                txtWPSandboxNavText.Enabled = true;
            }

            if ( ckbWPSandboxEnabled.Checked )
            {
                pnlWPSandboxNavText.Style.Add ( "display", "block" );
            }
            else
            {
                pnlWPSandboxEnabled.CssClass += " borderless";
                pnlWPSandboxNavText.Style.Add ( "display", "none" );
            }
        }
        #endregion

        #region Methods
        internal override bool Save ( )
        {
            if ( PermissionBitsProjects [ 2 ] )
            {
                if ( Project != null )
                {
                    Project.Title = txtProjectTitle.Text.Trim ( );
                    Project.ProjectStatus = ( ProjectStatus ) int.Parse ( rbProjectStatus.SelectedValue );

                    List<Attachment> attachments = Attachments.GetAttachments ( );

                    if ( attachments.Count > 0 )
                    {
                        Attachment attachment = attachments.Find ( x => x.Bytes != null && x.EditType != EditType.Deleted );
                        if ( attachment == null )
                            Project.ProjectPlanFileUrl = null;

                        Project.AttachmentList.AddRange ( attachments );
                    }
                    else
                    {
                        DateTime dt;

                        ValidationMessage message = null;
                        if ( DateTime.TryParse ( txtStartDate.Text, out dt ) || string.IsNullOrEmpty ( txtStartDate.Text ) )
                        {
                            Project.StartDate = string.IsNullOrEmpty ( txtStartDate.Text ) ? DateTimeHelpers.Empty : DateTime.Parse ( txtStartDate.Text );
                        }
                        else
                        {
                            message = new ValidationMessage ( ValidationSeverity.Validation, "Start date is not in the correct format. (e.g: 05/17/2007)" );
                            Project.StartDateMessage.Add ( message );
                        }

                        if ( DateTime.TryParse ( txtEndDate.Text, out dt ) || string.IsNullOrEmpty ( txtEndDate.Text ) )
                        {
                            Project.EndDate = string.IsNullOrEmpty ( txtEndDate.Text ) ? DateTimeHelpers.Empty : DateTime.Parse ( txtEndDate.Text );
                        }
                        else
                        {
                            message = new ValidationMessage ( ValidationSeverity.Validation, "End date is not in the correct format. (e.g: 05/17/2007)" );
                            Project.EndDateMessage.Add ( message );
                        }
                    }

                    if ( Project.SummaryNote != txtProjectSummary.Text )
                    {
                        Project.LastUpdatedSummaryNote = string.IsNullOrEmpty ( CurrentUser.FullName ) ? "Unknown" : CurrentUser.FullName;
                    }

                    Project.TimeMetric = ( TimeMetric ) int.Parse ( rblTimeMetric.SelectedValue );
                    Project.Description = txtProjectDescription.Text.Trim ( );
                    Project.SummaryNote = txtProjectSummary.Text;

                    Project.ServerRelativeUrl = ServerRelativeUrl;
                    Project.SiteCollectionId = SiteCollectionId;
                    Project.ModifiedBy = CurrentUser;
                    Project.ModifiedDate = DateTime.Now;

                    Project.CustomFieldNamesAndValues = CustomFields.HarvestCustomFieldValues ( );

                    Project.IsWPSandboxActivated = ckbWPSandboxEnabled.Checked;
                    Project.WPSandboxNavText = Project.IsWPSandboxActivated ? txtWPSandboxNavText.Text : default ( string );

                    Project.EditType = EditType.Updated;

                    Project = ProjectsModel.Save ( Project, SiteCollectionId, ServerRelativeUrl );
                    ValidateSave ( );
                }
            }
            return true;
        }

        internal override void Delete ( )
        {
            if ( PermissionBitsProjects [ 3 ] )
            {
                if ( SPHelpers.IsProject ( SiteCollectionId, ServerRelativeUrl ) )
                {
                    if ( Project != null )
                    {
                        Project.EditType = EditType.Deleted;
                        Project.ServerRelativeUrl = ServerRelativeUrl;
                        Project.ModifiedBy = CurrentUser;
                        if ( Project.IsValid ( ) )
                        {
                            string portalUrl = SPHelpers.GetPortalServerRelativeUrl ( SiteCollectionId, ServerRelativeUrl );
                            ProjectsModel.Save ( Project, SiteCollectionId, ServerRelativeUrl );

                            Response.Redirect ( portalUrl + Constants.PortalFileUrls.ProjectsActive );
                        }
                    }
                }
            }
        }

        internal override string Cancel ( )
        {
            return String.Format ( "{0}{1}", ServerRelativeUrl, Constants.ProjectFileUrls.ProjectSummary );
        }

        private void AddCommandButtons ( )
        {
            if ( PermissionBitsProjects [ 3 ] )
            {
                LinkButton btnDelete = new LinkButton ( );
                btnDelete.Text = "Delete this Project";
                btnDelete.Attributes.Add ( "class", "icon-delete" );
                string js = "javascript:{0}__doPostBack('ctl00$MainContent$V2NavigationSub$diidIODeleteItem','')";
                btnDelete.OnClientClick = string.Format ( js, "if (confirm('Are you sure that you want to delete this project?'))" );
                NavigationSub.Commands.Add ( btnDelete );
            }
        }

        private void ValidateSave ( )
        {
            if ( Project.IsValid ( ) )
            {
                KiiroMaster.V2ErrorsList.ErrorMessages.Clear ( );
                KiiroMaster.V2ErrorsList.ErrorMessages.Add ( "Project settings updated successfully." );
                KiiroMaster.V2ErrorsList.OperationStatus = OperationStatus.Success;
                PopulateForm ( );
            }
            else
            {
                KiiroMaster.V2ErrorsList.ErrorMessages.Clear ( );
                KiiroMaster.V2ErrorsList.ErrorMessages.Add ( "There are some submission errors with the form. Errors will be shown in red below the fields." );
                KiiroMaster.V2ErrorsList.OperationStatus = OperationStatus.Failure;
            }

            lblProjectTitleMessage.Text = FormattingHelpers.GetErrorMessageText ( Project.TitleMessage );
            lblProjectStatusMessage.Text = FormattingHelpers.GetErrorMessageText ( Project.ProjectStatusMessage );
            Attachments.ValidationMessage = FormattingHelpers.GetErrorMessageText ( Project.ProjectPlanBytesMessage );
            lblEndDateMessage.Text = FormattingHelpers.GetErrorMessageText ( Project.EndDateMessage );
            lblStartDateMessage.Text = FormattingHelpers.GetErrorMessageText ( Project.StartDateMessage );
            lblProjectDescriptionMessage.Text = FormattingHelpers.GetErrorMessageText ( Project.DescriptionMessage );
            lblProjectSummaryMessage.Text = FormattingHelpers.GetErrorMessageText ( Project.SummaryNoteMessage );
            lblWPSandboxNavTextMessage.Text = FormattingHelpers.GetErrorMessageText ( Project.WPSandboxNavTextMessage );
        }

        private void PopulateForm ( )
        {
            if ( Project != null )
            {
                ItemId = Project.Id;

                txtProjectTitle.Text = Project.Title;
                txtProjectDescription.Text = Project.Description;
                txtProjectSummary.Text = Project.SummaryNote;
                rbProjectStatus.SelectedValue = ( ( int ) Project.ProjectStatus ).ToString ( );

                rblTimeMetric.SelectedValue = ( ( int ) Project.TimeMetric ).ToString ( );

                txtStartDate.Text = Project.StartDate == default ( DateTime ) ? string.Empty : FormattingHelpers.DateTimeToDatePickerString ( Project.StartDate );
                txtEndDate.Text = Project.EndDate == default ( DateTime ) ? string.Empty : FormattingHelpers.DateTimeToDatePickerString ( Project.EndDate );

                ckbWPSandboxEnabled.Checked = Project.IsWPSandboxActivated;
                txtWPSandboxNavText.Text = Project.WPSandboxNavText;

                List<Attachment> attachments = new List<Attachment> ( );

                if ( !string.IsNullOrEmpty ( Project.ProjectPlanFileUrl ) )
                {
                    Attachment attachment = new Attachment ( );
                    attachment.FileName = Project.ProjectPlanFileUrl.Substring ( Project.ProjectPlanFileUrl.LastIndexOf ( "/" ) + 1 );
                    attachment.ServerRelativeUrl = Project.ProjectPlanFileUrl;
                    attachments.Add ( attachment );
                }

                Attachments.SetAttachments ( attachments );
            }
        }
        #endregion
    }
}

/*************************************************************************
 * 
 * $Log: /Internal Projects/Kiiro/Kiiro.SiteDefinition/12/TEMPLATE/FEATURES/Kiiro.ProjectPages/Projects/EditProjectSettings.aspx.cs $
 * 
 * 34    2/08/10 2:28p Camerons
 * 
 * 33    1/12/10 2:33p Camerons
 * 
 * 32    1/11/10 11:51a Camerons
 * 
 * 31    1/06/10 12:39p Camerons
 * 
 * 30    12/18/09 3:26p Camerons
 * 
 * 29    10/27/09 6:40p Adamw
 * 
 * 28    10/27/09 6:39p Adamw
 * fixed some issues around deleting plan files and saving project
 * settings
 * 
 * 27    10/27/09 5:53p Adamw
 * accomodations for moving plan file to document library:
 * -moved saving of plan out of ProjectsDA and into DocumentModel -->
 * DocumentDA
 * -added call to save project plan file to document library from
 * ProjectsModel
 * -changed New/Edit Project pages to pass in Attachment collection
 * 
 * 26    10/23/09 5:50p Adamw
 * Case 332 and added web part navigation tab validation to the page
 * 
 * 25    23/10/09 10:19a Shafia
 * 
 * 24    21/10/09 12:21p Shafia
 * 
 * 23    19/10/09 2:45p Shafia
 * 
 * 22    16/10/09 5:40p Shafia
 * Set Attachments Properties MaxLength, and FileFormat to allow one file
 * and .mpp files only.
 * 
 * 21    30/09/09 4:08p Camerons
 * Update all links that point to UserPages, pass User.SPUserId as the
 * ItemId so that we can safely run GetOrCreateUser
 * 
 * 20    29/09/09 12:40p Shafia
 * Implemented WebPart at project level
 * 
 * 19    2/09/09 4:48p Camerons
 * 
 * 18    31/08/09 12:18p Shafia
 * assigned Project.LastUpdatedSummaryNote if summary note changed
 * 
 * 17    17/08/09 11:07a Camerons
 * Added check-in comments section
 * 
 ************************************************************************/